package com.viknix.threadpool.manager.http.handler;

import com.viknix.threadpool.manager.common.util.IOUtils;
import com.viknix.threadpool.manager.http.Header;
import com.viknix.threadpool.manager.http.response.HttpClientResponse;
import com.viknix.threadpool.manager.http.result.HttpRestResult;
import org.apache.http.HttpStatus;

import java.lang.reflect.Type;

/**
 * @Author: Dongqi
 * @Date: 2021/11/22 10:57
 * @Version 1.0
 * @Description: Abstract response handler.
 */
public abstract class AbstractResponseHandler<T> implements ResponseHandler<T> {

    private Type responseType;

    @Override
    public final void setResponseType(Type responseType) {
        this.responseType = responseType;
    }

    @Override
    public final HttpRestResult<T> handle(HttpClientResponse response) throws Exception {
        if (HttpStatus.SC_OK != response.getStatusCode()) {
            return handleError(response);
        }
        return convertResult(response, this.responseType);
    }

    private HttpRestResult<T> handleError(HttpClientResponse response) throws Exception {
        Header headers = response.getHeaders();
        String message = IOUtils.toString(response.getBody(), headers.getCharset());
        return new HttpRestResult<T>(headers, response.getStatusCode(), null, message);
    }

    /**
     * Abstract convertResult method, Different types of converters for expansion.
     *
     * @param response     http client response
     * @param responseType responseType
     * @return HttpRestResult
     * @throws Exception ex
     */
    public abstract HttpRestResult<T> convertResult(HttpClientResponse response, Type responseType) throws Exception;

}
